package com.dy.yunying.api.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cx
 * @version 1.0.0
 * @Time 2021/10/26 10:31
 */
public class FileUtils {

	/**
	 * 获取txt文本内容 （获取礼包码）
	 * @param multipartFile
	 * @return
	 * @throws Exception
	 */
	public static List<String> readFileContent(MultipartFile multipartFile) {
		BufferedReader reader = null;
		List<String> list = new ArrayList<>();
		try {
			File file = FileUtils.multipartFileToFile(multipartFile);
			reader = new BufferedReader(new FileReader(file));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				tempStr = tempStr.trim();
				if (StringUtils.isNotBlank(tempStr) && tempStr.length() > 0) {
					list.add(tempStr);
				}
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return list;
	}

	/**
	 * MultipartFile 转 File
	 *
	 * @param file
	 * @throws Exception
	 */
	public static File multipartFileToFile(MultipartFile file) {
		try {
			File toFile = null;
			if (file.equals("") || file.getSize() <= 0) {
				file = null;
			} else {
				InputStream ins = null;
				ins = file.getInputStream();
				toFile = new File(file.getOriginalFilename());
				inputStreamToFile(ins, toFile);
				ins.close();
			}
			return toFile;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	//获取流文件
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除本地临时文件
	 * @param file
	 */
	public static void deleteTempFile(File file) {
		if (file != null) {
			File del = new File(file.toURI());
			del.delete();
		}
	}


}
